package com.viettel.core.memcached;

import com.viettel.core.common.utils.StringUtility;

/**
 * @author Doanhcdm
 */
public class FinderPath {
	private static final String PERIOD = ".";
	private static final String _ARGS_SEPARATOR = "_A_";
	private static final String _PARAMS_SEPARATOR = "_P_";
	
	private static String clientCacheId = "";
	
	public static void initClientCacheId(String clientCacheId) {
		FinderPath.clientCacheId = clientCacheId;
	}

	private String _localCacheKeyPrefix;
	private String _cacheKeyPrefix;
	private String _className;
	private String _methodName;
	private String[] _params;

	public FinderPath(String className, String methodName, String[] params) {

		_className = className;
		_methodName = methodName;
		_params = params;

		_initCacheKeyPrefix();
		_initLocalCacheKeyPrefix();
	}

	public String encodeCacheKey(Object[] args) {
		StringBuffer sb = new StringBuffer(args.length * 2 + 1);

		sb.append(_cacheKeyPrefix);

		for (Object arg : args) {
			sb.append(PERIOD);
			sb.append(String.valueOf(arg));
		}

		return StringUtility.getMD5Hash(sb.toString(), "");
	}

	public String encodeLocalCacheKey(Object[] args) {
		StringBuffer sb = new StringBuffer(args.length * 2 + 1);

		sb.append(_localCacheKeyPrefix);

		for (Object arg : args) {
			sb.append(PERIOD);
			sb.append(String.valueOf(arg));
		}

		return StringUtility.getMD5Hash(sb.toString(), "");
	}

	public String getClassName() {
		return _className;
	}

	public String getMethodName() {
		return _methodName;
	}

	public String[] getParams() {
		return _params;
	}

	private void _initCacheKeyPrefix() {
		StringBuffer sb = new StringBuffer();

		sb.append(_methodName);
		sb.append(_PARAMS_SEPARATOR);

		for (String param : _params) {
			sb.append(PERIOD);
			sb.append(param);
		}

		sb.append(_ARGS_SEPARATOR);

		_cacheKeyPrefix = sb.toString();
	}

	private void _initLocalCacheKeyPrefix() {
		_localCacheKeyPrefix = clientCacheId.concat(_className.concat(PERIOD)
				.concat(_cacheKeyPrefix));
	}

}